const async = require('async');
const getUploadService = require('../../modules/loopback-core/services/aws-s3-service');
const multiparty = require('multiparty');

module.exports = (req, res, cb) => {
  getUploadService(req).then((uploadService) => {
    const form = new multiparty.Form();
    // form.parse(req, function(err, fields, files) {
    //   let originalFilename = files.uploadFile[0].originalFilename;
    //   var ext = originalFilename.substring(originalFilename.lastIndexOf('.')+1,originalFilename.length);
    // })
    // .then
    if (!uploadService) {
      cb(new Error('File system has wrong configurations.'));
      return;
    }

    if (process.env.AWS_S3_IS_USED === 'true') {
        console.log(`S3 upload Service`);
      uploadAWSS3(uploadService, req, res, cb);
    } else {
        console.log(`No S3 Uplad Service`);
      uploadLocal(uploadService, req, res, cb);
    }
  }).catch((err) => {
    cb(err);
  });
};

function uploadLocal(uploadService, req, res, cb) {
  const folderName = getFolderName();

  const isExistFolder = (next) => {
    uploadService.getContainer(folderName, (error, folder) => {
      if (error && error.code === 'ENOENT') {
        next(null, folder);
        return;
      }
      next(error, folder);
    });
  };

  const createFolder = (folder, next) => {
    if (folder) return next(null, folder);
    uploadService.createContainer({ name: folderName }, next);
  };

  const uploadAttachment = (folder, next) => {
    uploadService.upload(req, res, { container: folder.name }, next);
  };

  async.waterfall([isExistFolder, createFolder, uploadAttachment], (error, result) => {
    if (error) {
      error.status = 501;
    }
    cb(error, result);
  });
}

function uploadAWSS3(uploadService, req, res, cb) {
  const folderName = process.env.AWS_S3_BUCKET_NAME;

  const uploadAttachment = (next) => {
    uploadService.upload(req, res, {
      container: folderName,
      prefix: getFolderName(),
    }, next);
  };

  async.waterfall([uploadAttachment], (error, result) => {
    if (error) {
      error.status = 501;
    }
    cb(error, result);
  });
}

function getFolderName() {
  return new Date().toISOString().split('T')[0];
}
